#!/usr/bin/node 

const http = require('http'), 
      fs = require('fs'),
      qs = require('querystring'),
      log = console.log;
var items = [],
    result = {
      status:200,
      reason:'ok',
      count:0,
      data:[]                           
    };

    
http.createServer((req, res) => {
  console.log(req.method);
  logRequest(req);
	
  if(req.url.slice(0,5) !== '/todo') {
	  var html = fs.readFileSync('./12-todo.html').toString('utf8');
	  if(req.url === '/') {
      res.end(html);		
	  } else if(req.url === '/12-todo.js') {
      console.log('jsjsjs');
      fs.createReadStream('./12-todo.js').pipe(res);
      return ;
    }
    else res.end('not api request..and not page request.');
    return ;
    //不是接口服务
  }

  switch(req.method) {
    case 'GET':
      select(req, res);
      //res.end('get method');
      break;

    case 'POST':
      insert(req, res);
      //res.end('post method');
      break;

    case 'PUT':
      update(req, res);
      //res.end('put method');
      break;

    case 'DELETE':
      remove(req, res);
      //res.end('delete method');
      break;

    default:
      res.end(`${req.method} method not support...`);
      break;
  }
  //res.end('hello cmt');
  
}).listen(8080);
//192.168.145.129:8080


function logRequest(req) {
  log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  log(req.headers);
  log('');
}

function select(req, res) {
  result.data = items;
  result.reason = 'select success';
  res.end(JSON.stringify(result));
}

function insert(req, res) {
  let data = '';

  req.on('data', chunk => data += chunk);
  req.on('end', () => {
    let item = qs.parse(data).item;

    if(item !== '' && typeof item !== undefined){
      //log(item);
      items.push(item);
	  result.reason = 'insert success';
      res.end(JSON.stringify(result));              
    }else{
      result.status = 401;
      result.reason = 'insert,item is empty';
      res.end(result);                       
    }        
  });
}


function update(req, res) {
  //get id
  //get item
  //update items[id] = item

  let arg = req.url.split(':'),
      id  = parseInt(arg[1]),
      data = '';
  //验证validate id
  //data type
  //min = 0, max = items.length
  req.on('data', chunk => data += chunk);
  req.on('end', () => {
    let item = qs.parse(data).item;
    if(item !== '' && typeof item !== 'undefined'){
      items[id] = item;
	  result.reason = 'update success';
      res.end(JSON.stringify(result));                   
    }else{
      result.status = 401;
      result.reason = 'item is empty';
      res.end(JSON.stringify(result));                       
    }      
  });
  //res.end(req.method);
}
function remove(req, res) {
  //git id
  let id = req.url.split(':')[1];
  log(req.url.split(':'));
  //id not exist : del all
  if(typeof id === 'undefined') {
    items = [];
    result.status = 200;
    result.reason = 'del all success';
    res.end(JSON.stringify(result));
    return ;
  }
  //id exist
  //id is ok del items[id]
  //valide id
  items = items.splice(id, 1);
  result.status = 200;
  result.reason = 'del id success';
  res.end(JSON.stringify(result));
}
